import { useState, useEffect } from 'react';
import Taro from '@tarojs/taro';
import { View, Text, Image, Input, Map } from '@tarojs/components';
import { AtIcon, AtRate } from 'taro-ui';

import "taro-ui/dist/style/components/rate.scss";
import "taro-ui/dist/style/components/icon.scss";

import './index.scss';
import apiRequest from '@/service/apiRequest';
import { IMG_URL } from '@/constants/api';

interface LocationInfo {
  latitude: number;
  longitude: number;
}

function HospitalSearch() {
  // const [keyword, setKeyword] = useState('');
  // const [activeTab, setActiveTab] = useState('全部');
  const [showMap, setShowMap] = useState(true);
  const [hospitals, setHospitals] = useState<any[]>([]);
  const [markers, setMarkers] = useState<any[]>([]);
  const [location, setLocation] = useState<LocationInfo>({ latitude: 39.9042, longitude: 116.4074 }); // 初始位置 北京
  
  // const tabs = ['全部', '24小时急诊', '专科医院', '宠物美容', '疫苗接种'];
  
  useEffect(() => {
    getLocationInfo().then((res: any) => {
      if (res) {
        setLocation(res);
        fetchNearbyHospitals(res);
      }
    });
  }, []);
  
  useEffect(() => {
    // 根据医院数据生成地图标记
    if (hospitals.length > 0) {
      const newMarkers = hospitals.map((hospital, index) => {
        let [longitude, latitude] = hospital.location.split(',');
        return {
          id: index,
          latitude: parseFloat(latitude),
          longitude: parseFloat(longitude),
          iconPath: `${IMG_URL}/marker.png`, // 需要添加标记图标
          width: 30,
          height: 30,
          callout: {
            content: hospital.name,
            color: '#000000',
            fontSize: 12,
            borderRadius: 5,
            padding: 5,
            display: 'ALWAYS'
          }
        }
      });
      setMarkers(newMarkers);
    }
  }, [hospitals]);

  const getLocationInfo = () => {
    return new Promise((resolve, reject) => {
      // 获取用户位置
      Taro.getLocation({
        type: 'gcj02',
        success: function (res) {
          resolve({latitude: res.latitude, longitude: res.longitude});
        },
        fail: function() {
          Taro.showToast({
            title: '获取位置失败，使用默认位置',
            icon: 'none'
          });
          resolve({});
        }
      });
      
    })

  };
  
  const fetchNearbyHospitals = async (location: LocationInfo) => {
    let result = await apiRequest.post("/api/nearby_hospitals", location);
    console.log(result, "result");
    if (result.pois) {
      setHospitals(result.pois);
    }
  };
  
  // const handleSearch = (value: string) => {
  //   setKeyword(value);
  //   // 实际应用中这里应该根据关键词搜索医院
  // };
  
  // const handleTabChange = (tab: string) => {
  //   setActiveTab(tab);
  //   // 实际应用中这里应该根据标签筛选医院
  // };
  
  const toggleMapView = () => {
    setShowMap(!showMap);
  };
  
  const callHospital = (phone: string) => {
    if (!phone) {
      Taro.showToast({
        title: '暂未提供电话信息',
        icon: 'none'
      });
      return
    }
    let phoneNumber = phone.split(";")[0];
    Taro.makePhoneCall({
      phoneNumber
    });
  };
  
  const navigateToLocation = (hospital) => {
    if (!hospital.location) {
      return
    }
    let [longitude, latitude] = hospital.location.split(',');
    Taro.openLocation({
      latitude: parseFloat(latitude),
      longitude: parseFloat(longitude),
      name: hospital.name,
      address: hospital.address,
      scale: 18
    });
  };
  
  // const makeAppointment = (id: string) => {
  //   Taro.navigateTo({
  //     url: `/nearbyHospitals/pages/appointment/index?id=${id}`
  //   });
  // };
  
  return (
    <View className='hospital-search-container'>
      {/* 搜索框 */}
      {/* <View className='search-bar'>
        <View className='search-input-wrapper'>
          <AtIcon value='search' size='18' color='#999' />
          <Input
            className='search-input'
            placeholder='搜索医院名称或服务'
            value={keyword}
            onInput={(e) => handleSearch(e.detail.value)}
          />
        </View>
        <View className='location-icon'>
          <AtIcon value='map-pin' size='22' color='#666' />
        </View>
      </View> */}
      
      {/* 筛选标签 */}
      {/* <View className='filter-tabs'>
        {tabs.map(tab => (
          <View 
            key={tab}
            className={`tab-item ${activeTab === tab ? 'active' : ''}`}
            onClick={() => handleTabChange(tab)}
          >
            {tab}
          </View>
        ))}
      </View> */}
      
      {/* 地图视图 */}
      {showMap && (
        <View className='map-container'>
          <Map
            className='map'
            longitude={location.longitude}
            latitude={location.latitude}
            markers={markers}
            showLocation
            scale={14}
            onError={(e) => console.log(e.detail)}
          />
          <View className='view-toggle' onClick={toggleMapView}>
            <Text>列表视图</Text>
            <AtIcon value='list' size='20' color='#333' />
          </View>
        </View>
      )}
      
      {/* 医院列表 */}
      <View className='hospital-list'>
        {hospitals.map((hospital, index) => (
          <View key={index} className='hospital-card'>
            <View className='hospital-info'>
              {
                hospital.photos && hospital.photos[0] ? (
                  <Image 
                    className='hospital-logo' 
                    src={hospital.photos[0].url}
                    mode='aspectFill'
                    webp
                  />
                ) : (
                  <View className='hospital-logo flex-c-c-c'>
                    <Image
                      className='hospital-e-img'
                      src={`${IMG_URL}/hos_fail_img.png`}
                      mode='aspectFill'
                    />
                  </View>
                )
              }
              <View className='hospital-details'>
                <Text className='hospital-name'>{hospital.name}</Text>
                {
                  hospital.business && hospital.business.rating ? (
                    <View className='rating-container'>
                      <AtRate value={parseFloat(hospital.business.rating)} size={16} />
                      <Text className='rating-text'>{hospital.business.rating}</Text>
                    </View>
                  ) : null
                }
                {
                  hospital.business && hospital.business.opentime_week ? (
                    <View className='business-box flex-a-c'>
                      <View>营业时间：</View>
                      <View className='week-t'>{ hospital.business.opentime_week }</View>
                    </View>
                  ) : null
                }
                <View className='tags-container'>
                  {/* {hospital.tags.map((tag, index) => (
                    <Text key={index} className='tag'>{tag}</Text>
                  ))} */}
                  {
                    hospital.type ? hospital.type.split(";").map((tag, index) => (
                      <Text key={index} className='tag'>{tag}</Text>
                    )) : null
                  }
                </View>
                <View className='address-container'>
                  <AtIcon value='map-pin' size='14' color='#999' />
                  <Text className='address-text'>{hospital.address}</Text>
                </View>
                {/* <View className='distance-container'>
                  <AtIcon value='clock' size='14' color='#999' />
                  <Text className='distance-text'>距离您{hospital.distance}公里 · 步行约{hospital.walkTime}分钟</Text>
                </View> */}
                {
                  hospital.distance ? (
                    <View className='distance-container'>
                      <AtIcon value='clock' size='14' color='#999' />
                      <Text className='distance-text'>距离您约{(parseFloat(hospital.distance)/1000).toFixed(1)}公里</Text>
                    </View>
                  ) : null
                }
              </View>
            </View>
            
            <View className='action-buttons'>
              <View className='action-btn' onClick={() => navigateToLocation(hospital)}>
                <AtIcon value='map-pin' size='16' color='#333' />
                <Text>导航</Text>
              </View>
              <View className='action-btn' onClick={() => callHospital(hospital.business ? hospital.business.tel : '')}>
                <AtIcon value='phone' size='16' color='#333' />
                <Text>电话</Text>
              </View>
              {/* <View className='appointment-btn' onClick={() => makeAppointment(hospital.id)}>
                <Text>预约</Text>
              </View> */}
            </View>
          </View>
        ))}
      </View>
    </View>
  );
}

export default HospitalSearch;